package com.autotemplate.util;

import com.autotemplate.util.vo.VelocityLongUtil;
import com.common.baseconstant.Convert;

import java.io.*;
import java.net.URISyntaxException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * function 对应着映射数据库，生成相应的实体类
 * Created by lhlong on 2016/12/5.
 */
public class GenerateDAO {

    private static final String[] tableNames = {"ad_orders","ad_service_account"};

    protected   Properties prop ;

    public  void generate(){
        this.prop = new Properties();

        String path = null;
        try {
            //读取配置文件路径信息
            path =GenerateDAO.class.getClassLoader().getResource("").toURI().getPath();
            System.out.println(File.separator);
            path = path  + "database.properties";
            InputStream in = new BufferedInputStream(new FileInputStream(path));
            prop.load(in);

            //创建JDBC连接
            Class.forName(prop.getProperty("DRIVER"));
            Connection conn = DriverManager.getConnection(prop.getProperty("URL"),prop.getProperty("USERNAME"),prop.getProperty("PASSWORD"));
            PreparedStatement ps = null ;
            Map<String,String> columnsInfoMap;
            String vmpath = "E:\\workspace_idea\\longautotheme\\src\\main\\java\\com\\autotemplate\\util\\vo";
            String destinationPath = "E:\\workspace_idea\\longautotheme\\src\\main\\java\\com\\autotemplate\\util\\file\\";
            Convert convert = new Convert();
            String destinationPath_tmp = destinationPath;

            for (String table:tableNames) {
                destinationPath = destinationPath_tmp + table +".java";
                VelocityLongUtil vlu = new VelocityLongUtil(vmpath,destinationPath,"Entity.vm");
                String sqlTmp = "SELECT * FROM " + table;
                ps = conn.prepareStatement(sqlTmp);
                ResultSet rs = ps.executeQuery();
                //使用ResultSetMetaData类获得对应的表的列数和列名
                ResultSetMetaData rsmd = rs.getMetaData();

                columnsInfoMap = new HashMap<String,String>(rsmd.getColumnCount());
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String columnName = rsmd.getColumnName(i+1);//列名
                    String columnTypeName = rsmd.getColumnTypeName(i+1);//列的数据类型名称
                    columnsInfoMap.put(convert.lowerCaseToPoJoName(columnName),convert.convertToJavaType(columnTypeName.toUpperCase()));
                }
                vlu.generateByValue(columnsInfoMap,convert.upperCaseToPoJoName(table));

            }

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        catch (IOException e1){
            e1.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }




}
